#include "AT24C02.h"
#include "MyI2C.h"

#define AT24C02_ADDRESS   0xa0

/**
  * @brief  AT24C02写入一个字节
  * @param  WordAddress要写入的地址
						Data要写入的数据
  * @retval 无
  */


void AT24C02_WriteByte(unsigned char WordAddress,uint8_t Data)
{
		MyI2C_Start();
		MyI2C_SendByte(AT24C02_ADDRESS);
		MyI2C_ReceiveAck();
		MyI2C_SendByte(WordAddress);
		MyI2C_ReceiveAck();
		MyI2C_SendByte(Data);
		MyI2C_ReceiveAck();
		MyI2C_Stop();
}

/**
  * @brief  AT24C02写入数组
  * @param  WordAddress要写入的地址
						Data要写入的数组地址
						Length要写入的数量
  * @retval 无
  */
void AT24C02_WritePage(unsigned char WordAddress,uint8_t* Data,uint8_t Length)
{
	int i;
		MyI2C_Start();
		MyI2C_SendByte(AT24C02_ADDRESS);
		MyI2C_ReceiveAck();
		MyI2C_SendByte(WordAddress);
		MyI2C_ReceiveAck();
		for(i=0;i<Length;i++)
		{
			MyI2C_SendByte(Data[i]);
			MyI2C_ReceiveAck();
		}
		
		MyI2C_Stop();
}

/**
  * @brief  AT24C02读取一个字节
  * @param  WordAddress要读出字节的地址
  * @retval 读出的数据
  */

unsigned char AT24C02_ReadByte(unsigned char WordAddress)
{
		unsigned char Data;
		MyI2C_Start();
		MyI2C_SendByte(AT24C02_ADDRESS);
		MyI2C_ReceiveAck();
		MyI2C_SendByte(WordAddress);
		MyI2C_ReceiveAck();
		MyI2C_Start();
		MyI2C_SendByte(AT24C02_ADDRESS|0x01);
		MyI2C_ReceiveAck();
		Data=MyI2C_ReceiveByte();
		MyI2C_SendAck(1);
		MyI2C_Stop();
	
		return Data;
}

/**
  * @brief  AT24C02读取OTA结构体信息
  * @param  无
  * @retval 无
  */
void M24C02_ReadOTAInfo(void)
{
	memset(&OTA_Info,0,OTA_INFOCB_SIZE);
	AT24C02_ReadPage(0,(uint8_t *)(&OTA_Info),OTA_INFOCB_SIZE);
}

/**
  * @brief  AT24C02更新OTA结构体信息
  * @param  无
  * @retval 无
  */
void M24C02_WriteOTAInfo(void)
{
	uint8_t i=0;
	uint8_t *wptr;
	wptr = (uint8_t *)&OTA_Info;
	
	for(i=0;i<OTA_INFOCB_SIZE/8;i++)
	{
		AT24C02_WritePage(i*8,(wptr+i*8),8);
	}
}


/**
  * @brief  AT24C02读取多个字节
  * @param  WordAddress要读出字节的地址
  * @retval 读出的数据
  */
void AT24C02_ReadPage(unsigned char WordAddress,uint8_t* Data,uint16_t Length)
{
		int i;
		MyI2C_Start();
		MyI2C_SendByte(AT24C02_ADDRESS);
		MyI2C_ReceiveAck();
		MyI2C_SendByte(WordAddress);
		MyI2C_ReceiveAck();
		MyI2C_Start();
		MyI2C_SendByte(AT24C02_ADDRESS|0x01);
		MyI2C_ReceiveAck();
		for(i=0;i<(Length-1);i++)
		{
			Data[i]=MyI2C_ReceiveByte();
			MyI2C_SendAck(0);
		}
		Data[i]=MyI2C_ReceiveByte();
		MyI2C_SendAck(1);
		
		MyI2C_Stop();
}

